package com.evolve.autotest;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.evolve.autotest.actions.ActionFactory;
import com.evolve.autotest.compiler.Compiler;
import com.evolve.autotest.compiler.CompilerException;
import com.evolve.autotest.util.FileUtil;

public class TestCaseLoader {

	private static final Logger logger = Logger.getLogger(TestCaseLoader.class);
	private final ActionFactory actionFactory;
	private Compiler compiler;

	/**
	 * Constructor
	 * @param actionFactory
	 */
	public TestCaseLoader(ActionFactory actionFactory) {
		this.actionFactory = actionFactory;
		compiler = new Compiler();
	}
	
	/**
	 * This will load all the tests in the test directory
	 * 
	 * It will load all test cases in any sub directory.
	 * 
	 * @param testDir
	 * @return a list of test cases. If the directory is empty or faulty a empty
	 *         list will be returned.
	 */
	public List<TestSuite> loadTestCases(String testDir) {

		logger.info("Loading test cases");
		
		List<TestSuite> tests = loadTestsFromDirectory(testDir);
		
		logger.info("Finished loading " + tests.size() + " test cases");
		
		return tests;
	}
	
	/**
	 * If test
	 * @param testDir
	 * @return
	 */
	private List<TestSuite> loadTestsFromDirectory(String testDir) {
		
		List<TestSuite> tests = new LinkedList<TestSuite>();

		if (testDir == null || testDir.length() == 0) {
			logger.error("Unable to load test cases. Test case directory was not a directory: " + testDir);
			return tests;
		}

		File directory = new File(testDir);

		if (directory == null || !directory.exists()) {
			logger.error("Unable to load test cases. Test case directory was not a directory: " + testDir);
			return tests;
		}

		File[] testFiles = directory.listFiles();

		if (testFiles == null) {
			logger.info("No test cases to load in directory " + directory.getAbsolutePath());
			return tests;
		}

		TestSuite suite;
		
		for (File file : testFiles) {
			if (file.isFile()) {
				
				try {
					logger.info("Compiling test " + FileUtil.extractSimpleName(file));
					suite = compiler.compile(file, actionFactory);
					tests.add(suite);
				} catch (CompilerException e) {
					logger.error("Unable to compile file " + file.getAbsolutePath(), e);
				}
				
			} else {
				// Directory
				tests.addAll(loadTestsFromDirectory(file.getAbsolutePath()));
			}
		}

		return tests;
	}
}
